package com.ruben.resolver;

import com.ruben.utils.AjaxJson;
import com.ruben.utils.ThrottledSlf4jLogger;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.RedisConnectionFailureException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @ClassName: GlobalExceptionResolver
 * @Description: 全局异常处理器
 * @Date: 2020/8/15 14:24
 * *
 * @author: achao<achao1441470436 @ gmail.com>
 * @version: 1.0
 * @since: JDK 1.8
 * @Slf4j 日志打印
 * @RestControllerAdvice @ResponseBody+@ControllerAdvice 增强注解
 */
@RestControllerAdvice
public class GlobalExceptionResolver {

    private static final Logger log = new ThrottledSlf4jLogger(LoggerFactory.getLogger(GlobalExceptionResolver.class), 2, TimeUnit.SECONDS);

    /**
     * 参数校验异常处理
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public AjaxJson parameterValidatorResolver(MethodArgumentNotValidException e) {
        List<FieldError> errors = e.getBindingResult().getFieldErrors();
        return AjaxJson.error(errors.stream().map(FieldError::getDefaultMessage)
                .collect(Collectors.joining(" ")));
    }

    @ExceptionHandler(value = RedisConnectionFailureException.class)
    public AjaxJson redisConnectionFailureResolver(RedisConnectionFailureException e) {
        log.error("redis连接失败", e);
        return AjaxJson.error("redis连接失败");
    }

    /**
     * 其他异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    public AjaxJson otherExceptionResolver(Exception e) {
        log.error("😄哈哈哈😄", e);
        return AjaxJson.error("嘻嘻嘻嘻哈哈哈😄");
    }
}
